<template>
  <uni-popup ref="addPopup" type="center" border-radius="20px">
    <view class="popup">
      <view class="head">
        <text>添加命令</text>
        <uni-icons type="clear" size="25" color="#aaa" style="opacity: 0.5" @click="closeAddCommand"></uni-icons>
      </view>
      <view class="body">
        <uni-forms ref="addCommandForm" :modelValue="addCommandInfo" :rules="addCommandInfoRules" label-position="left" label-width="80px">
          <uni-forms-item label="类型" name="script_type" required>
            <uni-data-select v-model="addCommandInfo.script_type" :localdata="script_type" clear></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="指令名称" name="name">
            <uni-easyinput type="text" :trim="true" v-model="addCommandInfo.name" placeholder="请输入指令名称" />
          </uni-forms-item>
          <uni-forms-item label="cmd命令/脚本" name="content" required>
            <uni-easyinput type="textarea" maxlength="-1" :trim="true" v-model="addCommandInfo.content" placeholder="请输入cmd命令或bat、vbs脚本" />
          </uni-forms-item>
          <uni-forms-item label="开启管理员权限" name="permission">
            <switch :checked="addCommandInfo.permission" @change="switchChangeHandler" />
          </uni-forms-item>
        </uni-forms>
        <button class="base-button" @click="addCommandEvent">{{ commandInfo.content ? "修改" : "添加" }}命令信息</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup name="commandForm">
import useComputerStore from "@/store/modules/computer.js";
import { ref, reactive } from "vue";
import { storeToRefs } from "pinia";
import _ from "lodash";
import { v4 as uuidv4 } from "uuid";
import { isAuthPass } from "../../utils/authentication";

const computerStore = useComputerStore();
const { computerList, commandList } = storeToRefs(computerStore);

const props = defineProps({
  computerInfo: {
    type: Object,
    default: {
      name: "",
      ip: "",
      port: "",
      custom_command: [],
    },
  },
});

let script_type = ref([
  { value: "cmd", text: "CMD命令" },
  { value: "bat", text: "BAT脚本" },
  { value: "vbs", text: "VBS脚本" },
]);

// 保存原有值
let commandInfo = reactive({
  script_type: "",
  name: "",
  content: "",
  permission: false,
});

// 添加命令窗口实例
const addPopup = ref();
// 打开添加命令窗口
const openAddCommand = (command) => {
  if (props.computerInfo) {
    if (command) {
      Object.assign(commandInfo, _.cloneDeep(command));
    } else {
      Object.assign(
        commandInfo,
        _.cloneDeep({
          script_id: "",
          script_type: "",
          name: "",
          content: "",
          permission: false,
        })
      );
    }
    Object.assign(addCommandInfo.value, _.cloneDeep(commandInfo));
  }
  addPopup.value.open("center");
};

// 关闭添加设备窗口
const closeAddCommand = () => {
  addPopup.value.close();
};

//添加设备表单校验规则
const addCommandInfoRules = {
  script_type: {
    rules: [
      {
        required: true,
        errorMessage: "请选择类型",
      },
    ],
    validateTrigger: "submit",
  },
  name: {
    // name 字段的校验规则
    rules: [],
    validateTrigger: "submit",
  },
  content: {
    rules: [
      {
        required: true,
        errorMessage: "cmd命令或脚本不可以为空",
      },
    ],
    validateTrigger: "submit",
  },
  permission: {
    format: Boolean,
    validateTrigger: "submit",
  },
};

// 添加指令表单
const addCommandInfo = ref({
  script_type: "",
  name: "",
  content: "",
  permission: false,
});

// 切换按钮
const switchChangeHandler = (e) => {
  addCommandInfo.value.permission = e.detail.value;
};

// 表单实例
const addCommandForm = ref();

// 添加设备事件
const addCommandEvent = async (index) => {
  if (isAuthPass()) return;
  let validateData = await addCommandForm.value.validate();
  let formData = _.cloneDeep(addCommandInfo.value);
  // 单个设备设置
  if (props.computerInfo.ip) {
    let computerIndex = computerList.value.findIndex((item) => item.ip === item.ip && item.port === item.port);
    // 修改命令
    if (commandInfo.script_id) {
      let index = props.computerInfo.custom_command.findIndex((item) => item.script_id === commandInfo.script_id);
      // let isRepetition = false;
      // for (let i = 0; i < props.computerInfo.custom_command.length; i++) {
      //   if (i === index) {
      //     continue;
      //   } else {
      //     if (props.computerInfo.custom_command[i].script_id === formData.script_id) {
      //       isRepetition = true;
      //       break;
      //     }
      //   }
      // }
      // if (isRepetition) {
      //   uni.showToast({
      //     title: "命令已存在",
      //     icon: "none",
      //   });
      // } else {
      let saveData = _.cloneDeep(computerList.value);
      saveData[computerIndex]["custom_command"][index] = formData;
      computerStore.updateComputerList(saveData);
      closeAddCommand();
      // }
    } else {
      formData.script_id = uuidv4();
      // 新增命令
      if (props.computerInfo.custom_command && props.computerInfo.custom_command.some((item) => item.script_id === formData.script_id)) {
        uni.showToast({
          title: "命令已存在",
          icon: "none",
        });
      } else {
        let saveData = _.cloneDeep(computerList.value);
        if (saveData[computerIndex]["custom_command"]) {
          saveData[computerIndex]["custom_command"].push(formData);
        } else {
          saveData[computerIndex]["custom_command"] = [formData];
        }
        computerStore.updateComputerList(saveData);
        closeAddCommand();
      }
    }
  } else {
    // 批量操作命令
    if (commandInfo.script_id) {
      let index = commandList.value.findIndex((item) => item.script_id === commandInfo.script_id);
      if (commandList.value.some((item) => item.script_id === formData.script_id && item.script_id !== commandInfo.script_id)) {
        uni.showToast({
          title: "命令已存在",
          icon: "none",
        });
      } else {
        let saveData = _.cloneDeep(commandList.value);
        saveData[index] = formData;
        computerStore.updateCommandList(saveData);
        closeAddCommand();
      }
    } else {
      formData.script_id = uuidv4();
      if (commandList.value.some((item) => item.script_id === formData.script_id)) {
        uni.showToast({
          title: "命令已存在",
          icon: "none",
        });
      } else {
        let saveData = _.cloneDeep(commandList.value);
        saveData.push(formData);
        computerStore.updateCommandList(saveData);
        closeAddCommand();
      }
    }
  }
};

defineExpose({ openAddCommand });
</script>

<style lang="scss" scoped>
.popup {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 10rpx;
  box-sizing: border-box;
  padding: 20rpx;
  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;

    text {
      font-size: 35rpx;
      font-weight: bold;
      color: #333;
    }
  }
  .body {
    margin-top: 20px;
  }
}
</style>
